const loki = require('lokijs')
const fs = require('fs')
const request = require('superagent');
// 启动log
const log4js = require('log4js');
log4js.configure({
    appenders: { cheese: { type: 'file', filename: './avatarFaile.log' } },
    categories: { default: { appenders: ['cheese'], level: 'trace' } }
});
const logger = log4js.getLogger('cheese');


var db = new loki('./SD_DB.db', {
    autoload: true,
    autoloadCallback: databaseInitialize,
    autosave: true,
    autosaveInterval: 4000
});

// implement the autoloadback referenced in loki constructor
function databaseInitialize() {
    var robots = db.getCollection("robots");
    if (robots === null) {
        robots = db.addCollection("robots");
    }
    // kick off any program logic or start listening to external events
    runProgramLogic(robots);
}


function createRobotDB(robots) {
    var robotJSON = JSON.parse(fs.readFileSync('./SDdata.json'))
    robots.insert(robotJSON)
}

let machineMap = {}
let madchineArr = []
function runProgramLogic(robots) {
    let res = robots.find({})
    console.log(`已加载${res.length}条数据库内容`)
    var i = 0
    getPic(i)
    function getPic(i) {
        let num = res[i].ID;
        request.get(`https://www.olgame.tw/sds/images/robot/${num}.gif`)
            .then(res => {
                // let num = robotpicPath.match(/\d+\.gif/)
                // fs.writeFileSync(`./fxImg/${num}`, res.text)
                fs.writeFile(`./GundamAvatar/${num}.gif`, res.body, (err) => {
                    if (err) {
                        console.log(`存储图片失败，编号${num}`)
                    }
                    console.log(`头像存储-${num}成功`)
                    console.log(`${i}条`)
                    getPic(++i)
                })
            }).catch(err => {
                console.log(`头像存储-${num}faile, again` + err);
                // fs.writeFileSync(`./GundamAvatar/errLog.log`, `头像存储-${num}faile`)
                logger.error(`头像存储-${num}faile`)
                if (err.status == 404) {
                    getPic(++i)
                } else {
                    getPic(i)
                }
            })
    }
    // robots.update(res)
    // console.log('更新tags完毕')
    // db.save()
}



module.exports = db;